﻿using Microsoft.EntityFrameworkCore;
using SJ.Platform.Common;
using SJ.Platform.EFCore.Model;
using SJ.Platform.EFCore.Model.UserManager;
using SJ.Platform.Extend.ModelExtend;
using SJ.Platform.Extend.ModelExtend.SysUserExt;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace SJ.Platform.EFCore.DBOperation.DBOperation.MySQL.Sys
{
    /// <summary>
    /// 用户操作类
    /// </summary>
    public class Sys_UserHandle
    {
        private readonly SJDBContext _context;

        public Sys_UserHandle(SJDBContext context)
        {
            _context = context;
        }

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<bool> CreateAsync(SysUser entity)
        {
            try
            {
                _context.SysUsers.Add(entity);
                await _context.SaveChangesAsync();
                return true;
            }
            catch (Exception ex)
            {
                LogManager.WriteError("Sys_UserHandle=>Create", ex);
                return false;
            }
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<bool> UpdateAsync(SysUser entity)
        {
            try
            {
                _context.Entry(entity).State = EntityState.Modified;
                await _context.SaveChangesAsync();
                return true;
            }
            catch (Exception ex)
            {
                LogManager.WriteError("Sys_UserHandle=>Update", ex);
                return false;
            }
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<bool> UpdateOrgAsync(string orgId, string orgName)
        {
            try
            {
                var users = await _context.SysUsers.Where(u => u.OrgId == orgId).ToListAsync();
                int count = _context.Database.ExecuteSqlRaw($"update sys_user set OrgName='{orgName}' where OrgId='{orgId}';");
                return users.Count == count;
            }
            catch (Exception ex)
            {
                LogManager.WriteError("Sys_UserHandle=>Update", ex);
                return false;
            }
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public bool Delete(SysUser entity)
        {
            try
            {
                _context.SysUsers.Remove(entity);
                return _context.SaveChanges() > 0;
            }
            catch (Exception ex)
            {
                LogManager.WriteError("Sys_UserHandle=>Delete", ex);
                return false;
            }
        }

        /// <summary>
        /// 根据主键删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<bool> DeleteByIdAsync(string id)
        {
            try
            {
                var entity = _context.SysUsers.FindAsync(id).Result;
                if (entity != null)
                {
                    _context.SysUsers.Remove(entity);
                    await _context.SaveChangesAsync();
                    return true;
                }
            }
            catch (Exception ex)
            {
                LogManager.WriteError("Sys_UserHandle=>DeleteById", ex);
            }
            return false;
        }

        /// <summary>
        /// 根据ID获取实体
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<SysUser> GetEntityByIdAsync(string id)
        {
            try
            {
                return await _context.SysUsers.FindAsync(id);
            }
            catch (Exception ex)
            {
                LogManager.WriteError("Sys_UserHandle=>GetEntityById", ex);
            }
            return null;
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="pageNumber"></param>
        /// <param name="pageSize"></param>
        /// <param name="condition"></param>
        /// <returns></returns>
        public List<SysUser> GetAll(int pageNumber, int pageSize, ref int count, Expression<Func<SysUser, bool>> condition = null)
        {
            try
            {
                var query = _context.SysUsers.AsQueryable();

                // 如果提供了查询条件，则应用它
                if (condition != null)
                {
                    query = query.Where(condition);
                }
                count = query.Count();
                // 应用分页
                var skip = (pageNumber - 1) * pageSize;
                query = query.Skip(skip).Take(pageSize);

                // 执行查询并返回结果
                return query.ToList();
            }
            catch (Exception ex)
            {
                LogManager.WriteError("Sys_UserHandle=>GetAll  page", ex);
            }
            return null;
        }
        /// <summary>
        /// 根据组织机构ID获取用户
        /// </summary>
        /// <param name="pageNumber"></param>
        /// <param name="pageSize"></param>
        /// <param name="orgIds"></param>
        /// <returns></returns>
        public async Task<(List<SysUserAddExtend> usersExt, int count)> GetAllByOrgAsync(int pageNumber, int pageSize, List<SysOrgExtend> orgList, Expression<Func<SysUser, bool>> condition = null)
        {
            try
            {
                List<string> orgIdList = new List<string>();
                GetOrgIds(orgList, orgIdList);
                // 查询用户
                var query = _context.SysUsers.AsQueryable()
                                  .Where(u => orgIdList.Contains(u.OrgId));
                if (condition != null)
                {
                    query = query.Where(condition);
                }

                // 获取总行数
                int count = await query.CountAsync();

                // 应用分页
                var skip = (pageNumber - 1) * pageSize;
                query = query.Skip(skip).Take(pageSize);

                // 执行查询并返回结果
                var users = await query.ToListAsync();

                List<SysUserAddExtend> usersExt = new List<SysUserAddExtend>();
                if (users != null && users.Count > 0)
                {
                    usersExt = users.Select(user => new SysUserAddExtend
                    {
                        Id = user.Id,
                        RealName = user.RealName,
                        OrgId = user.OrgId,
                        OrgName = user.OrgName,
                        Sex = user.Sex,
                        Birthday = user.Birthday,
                        IsUsed = user.IsUsed,
                        AddTime = user.AddTime,
                        AddUserId = user.AddUserId,
                        EditTime = user.EditTime,
                        EditUserId = user.EditUserId,
                    }).ToList();

                    List<string> uIdList = new List<string>();
                    foreach (SysUser user in users)
                    {
                        if (!uIdList.Contains(user.Id))
                        {
                            uIdList.Add(user.Id);
                        }
                    }

                    List<SysLogin> loginUserList = _context.SysLogins.FromSqlRaw("select Id,LoginName,Password,IsUsed FROM sys_login where Id in ('" + string.Join("','", uIdList.ToArray()) + "')").ToList();

                    foreach (SysUserAddExtend user in usersExt)
                    {
                        user.LoginName = loginUserList.Find(o => o.Id == user.Id) != null ? loginUserList.Find(o => o.Id == user.Id).LoginName : "";
                        user.Password = loginUserList.Find(o => o.Id == user.Id) != null ? loginUserList.Find(o => o.Id == user.Id).Password : "";
                    }
                }

                return (usersExt, count);
            }
            catch (Exception ex)
            {
                LogManager.WriteError("Sys_UserHandle=>GetAllByOrgIdAsync", ex);
            }
            return (null, 0);
        }

        private void GetOrgIds(List<SysOrgExtend> orgList, List<string> orgIdList)
        {
            foreach (SysOrgExtend org in orgList)
            {
                if (!orgIdList.Contains(org.Id))
                {
                    orgIdList.Add(org.Id);
                }

                if (org.childOrgList != null && org.childOrgList.Count > 0)
                {
                    GetOrgIds(org.childOrgList, orgIdList);
                }
            }
        }

        /// <summary>
        /// 获取所有用户
        /// </summary>
        /// <param name="condition"></param>
        /// <returns></returns>
        public async Task<List<SysUser>> GetAll(Expression<Func<SysUser, bool>> condition = null)
        {
            try
            {
                IQueryable<SysUser> query = _context.SysUsers;

                // 如果提供了查询条件，则应用它
                if (condition != null)
                {
                    query = query.Where(condition);
                }

                // 执行查询并返回结果
                return await query.ToListAsync();
            }
            catch (Exception ex)
            {
                LogManager.WriteError("Sys_UserHandle=>GetAll", ex);
            }
            return null;
        }

        /// <summary>
        /// 根据角色获取所有用户
        /// </summary>
        /// <param name="condition"></param>
        /// <returns></returns>
        public async Task<List<SysUser>> GetAllByRoleId(string roleId)
        {
            try
            {
                var query = from user in _context.SysUsers
                            join r in _context.SysRForeigntoroles on user.Id equals r.ForeignId
                            where r.RoleId == roleId && r.ForeignType == 1
                            select user;

                // 执行查询并返回结果
                return await query.ToListAsync();
            }
            catch (Exception ex)
            {
                LogManager.WriteError("Sys_UserHandle=>GetAllByRoleId", ex);
            }
            return null;
        }
    }
}